﻿using AutoMapper;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.User;
using System.Linq;

namespace RBAC.Read.Api.Application.Handler.User
{
    public class GetUserListHandler : IRequestHandler<GetUserListCommand, APIPaging<GetUserListDto>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<UserRoleModel> userroleRepository;
        private readonly ILogger<GetUserListHandler> logger;
        private readonly IMapper mapper;
        
        public GetUserListHandler(IBaseRepository<UserModel> userRepository, 
            IBaseRepository<RoleModel> roleRepository, 
            IBaseRepository<UserRoleModel> userroleRepository, 
            IMapper mapper, 
            ILogger<GetUserListHandler> logger)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.userroleRepository = userroleRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<GetUserListDto>> Handle(GetUserListCommand request, CancellationToken cancellationToken)
        {
            APIPaging<GetUserListDto> res = new APIPaging<GetUserListDto>();
            
            try
            {
                // 构建用户查询条件
                string userWhereClause = "";
                object userParameters = new { };
                
                if (!string.IsNullOrEmpty(request.UserName))
                {
                    userWhereClause = "UserName LIKE @UserName";
                    userParameters = new { UserName = $"%{request.UserName}%" };
                }

                // 使用Dapper获取数据
                var users = userRepository.GetAll(userWhereClause, userParameters);
                var userroles = userroleRepository.GetAll();
                var roles = roleRepository.GetAll();

                // 构建JOIN查询SQL
                var joinSql = @"
                    SELECT 
                        u.Id,
                        u.UserName,
                        u.Password,
                        u.IsEnable,
                        r.RoleName,
                        r.Id as RoleId
                    FROM User u
                    INNER JOIN UserRole ur ON u.Id = ur.UserId
                    INNER JOIN Role r ON ur.RoleId = r.Id
                    WHERE u.IsDeleted = false 
                        AND ur.IsDeleted = false 
                        AND r.IsDeleted = false";

                // 添加用户名过滤条件
                if (!string.IsNullOrEmpty(request.UserName))
                {
                    joinSql += " AND u.UserName LIKE @UserName";
                }

                // 执行JOIN查询
                var userRoleData = userRepository.Query<dynamic>(joinSql, userParameters);

                // 按用户分组，将每个用户拥有的角色名称存储到集合中
                var groupedData = userRoleData
                    .GroupBy(x => new { x.Id, x.UserName, x.Password, x.IsEnable })
                    .Select(g => new GetUserListDto
                    {
                        Id = g.Key.Id,
                        UserName = g.Key.UserName,
                        Password = g.Key.Password,
                        RoleName = g.Select(r => (string)r.RoleName).ToList(),
                        RoleId = g.Select(r => (long)r.RoleId).ToList(),
                        IsEnable = g.Key.IsEnable
                    }).ToList();

                // 分页处理
                var pagedData = groupedData
                    .Skip((request.Pageindex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                res.Code = APIEnums.Success;
                res.PageDatas = pagedData;
                res.TotalCount = groupedData.Count;
                res.Msg = "获取用户列表成功";
                logger.LogInformation("获取用户列表成功");
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Error;
                res.Msg = "获取用户列表失败";
                logger.LogError(ex, "获取用户列表失败: {Message}", ex.Message);
            }

            return Task.FromResult(res);
        }
    }
}
